<script setup lang="ts">
import { h, resolveComponent } from "vue";
import type { TableColumn } from "@nuxt/ui";
import type { Row } from "@tanstack/vue-table";
import type { User } from "~~/shared/types/user.types";

const UButton = resolveComponent("UButton");
const UBadge = resolveComponent("UBadge");
const UDropdownMenu = resolveComponent("UDropdownMenu");

const toast = useToast();
const router = useRouter();

const columns: TableColumn<User>[] = [
  {
    accessorKey: "username",
    header: "用户名",
  },
  {
    accessorKey: "email",
    header: "邮箱",
  },
  {
    accessorKey: "role",
    header: "角色",
    cell: ({ row }) => {
      const color = {
        admin: "primary" as const,
        user: "neutral" as const,
      }[row.getValue("role") as string];

      const label = {
        admin: "管理员",
        user: "普通用户",
      }[row.getValue("role") as string];

      return h(
        UBadge,
        { class: "capitalize", variant: "subtle", color },
        () => label
      );
    },
  },
  {
    accessorKey: "createdAt",
    header: "创建时间",
    cell: ({ row }) => {
      return new Date(row.getValue("createdAt")).toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    },
  },
  {
    id: "actions",
    cell: ({ row }) => {
      return h(
        "div",
        { class: "text-right" },
        h(
          UDropdownMenu,
          {
            content: {
              align: "end",
            },
            items: getRowItems(row),
            "aria-label": "操作菜单",
          },
          () =>
            h(UButton, {
              icon: "i-lucide-ellipsis-vertical",
              color: "neutral",
              variant: "ghost",
              class: "ml-auto",
              "aria-label": "操作菜单",
            })
        )
      );
    },
  },
];

function getRowItems(row: Row<User>) {
  return [
    {
      type: "label",
      label: "操作",
    },
    {
      label: "编辑用户",
      icon: "i-lucide-edit",
      onSelect() {
        toast.add({
          title: `准备编辑用户: ${row.original.username}`,
          color: "info",
          icon: "i-lucide-info",
        });
      },
    },
    {
      label: row.original.role === "user" ? "设为管理员" : "设为普通用户",
      icon: row.original.role === "user" ? "i-lucide-shield" : "i-lucide-user",
      onSelect() {
        const newRole = row.original.role === "user" ? "admin" : "user";
        const message = newRole === "admin" ? "已设为管理员" : "已设为普通用户";

        toast.add({
          title: message,
          color: "success",
          icon: "i-lucide-check",
        });
      },
    },
    {
      type: "separator",
    },
    {
      label: "删除用户",
      icon: "i-lucide-trash",
      color: "error" as const,
      async onSelect() {
        const { error } = await useFetch(`/api/user/${row.original.id}`, {
          method: "DELETE",
        });

        if (error.value) {
          toast.add({
            title: "删除失败",
            description: error.value.data?.message || "未知错误",
            color: "error",
            icon: "i-lucide-alert-circle",
          });
          return;
        }

        toast.add({
          title: "删除成功",
          description: `用户 ${row.original.username} 已被删除`,
          color: "success",
          icon: "i-lucide-check",
        });

        // 刷新用户列表
        refresh();
      },
    },
  ];
}

const {
  data: users,
  status,
  error,
  refresh,
} = useFetch<User[]>("/api/user", {
  default: () => [],
});
</script>
<template>
  <div class="p-4">
    <div class="flex justify-between items-center mb-4">
      <h1 class="text-2xl font-bold">用户管理</h1>
      <UButton
        color="primary"
        icon="i-lucide-plus"
        label="新增用户"
        @click="router.push('/system/user/create')"
      />
    </div>

    <UCard>
      <!-- Use status for conditional rendering -->
      <div
        v-if="status === 'pending'"
        class="flex justify-center items-center p-4"
      >
        <p>加载中...</p>
      </div>
      <div v-else-if="status === 'error'" class="text-red-500 p-4">
        加载用户数据时出错: {{ error?.message || "未知错误" }}
        <UButton label="重试" variant="link" @click="refresh" />
      </div>
      <UTable
        v-else-if="status === 'success'"
        :data="users"
        :columns="columns"
        class="w-full"
      />
    </UCard>
  </div>
</template>
